package br.com.cdto.mb;

import java.io.Serializable;
import java.security.Principal;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.primefaces.component.layout.LayoutUnit;
import org.primefaces.event.CloseEvent;
import org.primefaces.event.ToggleEvent;

@ManagedBean
@ViewScoped
public class LayoutMB implements Serializable {
	private static final long serialVersionUID = 1936752150041162380L;
	
	private String userName;
	private boolean loged;
	
	@PostConstruct
	public void init(){
		try{
			FacesContext context = FacesContext.getCurrentInstance();
	        HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
	        Principal principal = request.getUserPrincipal();
	    
			setUserName(principal.getName());
			loged = true;
		}catch(Exception e){
			setUserName(" ");
			loged = false;
		}
	}

    
    public String logout() {
        String result="/index?faces-redirect=true";
         
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
        
        try {
        	HttpSession session = request.getSession(true); 
        	session.invalidate(); 
        } catch (Exception e) {
        	System.out.println("errolayout");
        	result = "/erroLogin?faces-redirect=true";
        }
        
        return result;
      }
    
    public String login() {
		return"/login?faces-redirect=true";
	}
    
    public String toCornea() {
		return"/admin/cornea?faces-redirect=true";
	}
      
    private void addMessage(FacesMessage message) {  
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    public String toIndex(){
		return "/admin/index?faces-redirect=true";
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public boolean isLoged() {
		return loged;
	}

	public void setLoged(boolean loged) {
		this.loged = loged;
	}

}
